# -*- coding: utf-8 -*-
# @Author : gongyu
# @Date   : 2019/4/8
# @File   : EC04_ExtGuarBalToCapitalPro.py
# @E-mail : gongyu@bbdservice.com

'''eof
name:企业未来6个月未结清到期贷款余额比月均申报收入总额
code:EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro_SX_2D
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D,TX_SX_DSJ
type:常用指标
dataSourceType:
eof'''


import sys
import re
import datetime
import pandas as pd
from collections import OrderedDict
from dateutil.relativedelta import relativedelta

reload(sys)
sys.setdefaultencoding('utf-8')

last_month_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d')[:6] \
                    for i in range(1, 30)]
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)




def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def Later6MonsUpaidLoanBalPre():
    data = EC_DSJ_2D['data']
    # 借贷账户信息   [1..1]
    EDA = getTable(data, "EDA", 1)
    if EDA is None:
        return None
    elif EDA == [{}] or EDA == "":
        return 0
    else:
        # 借贷账户信息单元   [0..*]
        ED01 = getTable(EDA[0], "ED01", 0)
        if ED01 in null_type_list:
            return None
        elif ED01 ==[{}]:
            return 0
        else:
            factor = []
            for i in ED01:
                try:
                    # 基本信息段   [1..1]
                    ED01A = getTable(i, 'ED01A', 1)
                    # 还款信息段   [1..1]
                    ED01B = getTable(i, 'ED01B', 1)
                    if ED01A in null_type_list:
                        factor.append(None)
                    elif ED01A == [{}]:
                        factor.append(0)
                    else:
                        # 账户活动状态   [1..1]
                        ED01AD01 = ED01A[0].get('ED01AD01')
                        # 到期日期   [0..1]
                        ED01AR02 = ED01A[0].get('ED01AR02')
                        # 借贷账户类型 ED01AD02
                        ED01AD02 = ED01A[0].get('ED01AD02')
                        if ED01AD01 in null_type_list or formatDate(ED01AR02) in null_type_list or ED01AD02 in null_type_list:
                            factor.append(None)
                        else:
                            now = datetime.datetime.now()
                            six_months = datetime.timedelta(days = 6*30)
                            end_date = (now + six_months)
                            #1-未结清
                            if ED01AD01 == '1' and  formatDate(ED01AR02) > now and formatDate(ED01AR02) <= end_date and ED01AD02 != 'D2':
                                if ED01B in null_type_list:
                                    factor.append(None)
                                elif ED01B == [{}]:
                                    factor.append(0)
                                else:
                                    # 还款表现信息   [0..*]
                                    ED01BH = getTable(ED01B[0],'ED01BH', 0)
                                    if ED01BH in null_type_list:
                                        factor.append(None)
                                    elif ED01BH == [{}]:
                                        factor.append(0)
                                    else:
                                        for i in ED01BH:
                                            # 余额   [1..1]
                                            ED01BJ01 = i.get('ED01BJ01')
                                            if isfloat(ED01BJ01):
                                                factor.append(float(ED01BJ01))
                                            else:
                                                factor.append(None)
                            else:
                                factor.append(0)
                except:
                    factor.append(None)
                    continue
            factor = filter(lambda x: x is not None, factor)
            if len(factor) == 0:
                factor = None
            else:
                factor = sum(factor)
            return factor


#1-月均申报收入总额计算
null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTableTX(table_Name):
    try:
        ic_data = TX_SX_DSJ['data'].get(table_Name)
        if ic_data is None:
            return None
        else:
            return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]
    except:
        return None


# 纳税人类型
def TaxerType():
    try:
        syptSwdjxx = getTableTX('syptSwdjxx')
        if syptSwdjxx == [{}] or syptSwdjxx is None:
            return None
        else:
            NSRZG_DM = syptSwdjxx[0].get('NSRZG_DM')
            if NSRZG_DM in null_type_list:
                return None
            elif NSRZG_DM not in null_type_list and NSRZG_DM in ['201', '202', '203', '204', '205']:
                return NSRZG_DM
            else:
                return u'其他'
    except:
        return None

# 一般纳税人
def ybnsr():
    try:
        syptZzsybnsr = getTableTX('syptZzsybnsr')
        if syptZzsybnsr is None or syptZzsybnsr == [{}]:
            return 'None'
        else:
            # 可能存在统一年月 存在多次数据需要 用dict去重
            Reven_list = OrderedDict()
            for k in last_month_list:
                Reven_list.update({k:'None'})
            flag = []
            for i in syptZzsybnsr:
                QSRQ = i.get('skssqq')
                QZRQ = i.get('skssqz')
                if QSRQ in null_type_list or QZRQ in null_type_list or formatDate(QSRQ) == None or formatDate(QZRQ) == None:
                    flag.append(None)
                    continue
                else:
                    # QSNY = str(QSRQ[:4])+str(QSRQ[5:7])
                    # QZNY = str(QZRQ[:4])+str(QZRQ[5:7])
                    Mons = (int(QZRQ[:4])-int(QSRQ[:4]))*12 + (int(QZRQ[5:7])-int(QSRQ[5:7]))
                    noneCont = 0
                    if(Mons==0):
                        ND = QSRQ[:4]
                        YF = QSRQ[5:7]
                        # noneCont = 0
                        if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                               '08', '09', '10', '11', '12']:
                            # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                            if isfloat(i.get('ASYSLJSDNSJCYBJSE')):
                                a1 = float(i.get('ASYSLJSDNSJCYBJSE'))
                            else:
                                a1 = None
                                noneCont += 1
                            # “按简易办法计税销售额(AJYZSBFZSHWXSE)”
                            if isfloat(i.get('AJYZSBFZSHWXSE')):
                                a2 = float(i.get('AJYZSBFZSHWXSE'))
                            else:
                                a2 = None
                                noneCont += 1
                            # 免、抵、退办法出口销售额(MDTBFCKHWXSE)
                            if isfloat(i.get('MDTBFCKHWXSE')):
                                a3 = float(i.get('MDTBFCKHWXSE'))
                            else:
                                a3 = None
                                noneCont += 1
                            # 免税销售额(MSHWJLWXSE)
                            if isfloat(i.get('MSHWJLWXSE')):
                                a4 = float(i.get('MSHWJLWXSE'))
                            else:
                                a4 = None
                                noneCont += 1
                            if noneCont == 4 :
                                pass
                            elif a1==a2==a1==a3==a4==None:
                                pass
                            else:
                                if a1 == None:
                                    a1=0
                                if a2 == None:
                                    a2=0
                                if a3 == None:
                                    a3=0
                                if a4 == None:
                                    a4=0
                                # 存入每个月的收入
                                Reven_Value = a1+a2+a3+a4
                                key = str(ND) + str(YF)
                                if Reven_list.get(key) == 'None':
                                    Reven_list.update({key: Reven_Value})
                        else:
                            flag.append(None)
                            continue
                    elif(Mons>0):
                            # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                            if isfloat(i.get('ASYSLJSDNSJCYBJSE')):
                                a1 = float(i.get('ASYSLJSDNSJCYBJSE'))
                            else:
                                a1 = None
                                noneCont += 1
                            # “按简易办法计税销售额(AJYZSBFZSHWXSE)”
                            if isfloat(i.get('AJYZSBFZSHWXSE')):
                                a2 = float(i.get('AJYZSBFZSHWXSE'))
                            else:
                                a2 = None
                                noneCont += 1
                            # 免、抵、退办法出口销售额(MDTBFCKHWXSE)
                            if isfloat(i.get('MDTBFCKHWXSE')):
                                a3 = float(i.get('MDTBFCKHWXSE'))
                            else:
                                a3 = None
                                noneCont += 1
                            # 免税销售额(MSHWJLWXSE)
                            if isfloat(i.get('MSHWJLWXSE')):
                                a4 = float(i.get('MSHWJLWXSE'))
                            else:
                                a4 = None
                                noneCont += 1
                            if noneCont == 4:
                                pass
                            elif a1==a2==a1==a3==a4==None:
                                pass
                            else:
                                # 存入收入
                                if a1 == None:
                                    a1=0
                                if a2 == None:
                                    a2=0
                                if a3 == None:
                                    a3=0
                                if a4 == None:
                                    a4=0
                                Reven_Value = a1+a2+a3+a4
                                Reven_Ave = round(float(Reven_Value)/(Mons+1),4)
                                for  j in range(Mons+1):
                                    NDYF = datetime.datetime.strptime(QSRQ,'%Y-%m-%d') + relativedelta(months=j)
                                    ND = str(NDYF)[:4]
                                    YF = str(NDYF)[5:7]
                                    # noneCont = 0
                                    if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                               '08', '09', '10', '11', '12']:
                                        key = str(ND) + str(YF)
                                        if Reven_list.get(key) == 'None':
                                            Reven_list.update({key: Reven_Ave})
                                        else:
                                            pass
                                    else:
                                        flag.append(None)
                                        continue
                    else:
                        flag.append(None)
                        continue
            if len(flag) == len(syptZzsybnsr):
                Reven_list = 'None'
            return Reven_list
    except:
        return 'None'

# 小规模纳税人
#小规模纳税人
def xgm():
    try:
        syptZzsxgm = getTableTX('syptZzsXgm')
        if syptZzsxgm is None or syptZzsxgm == [{}]:
            return 'None'
        else:
            Reven_list = OrderedDict()
            for k in last_month_list:
                Reven_list.update({k:'None'})
            flag = []
            for i in syptZzsxgm:
                QSRQ = i.get('skssqq')
                QZRQ = i.get('skssqz')
                if QSRQ in null_type_list or QZRQ in null_type_list or formatDate(QSRQ) == None or formatDate(QZRQ) == None:
                    flag.append(None)
                    continue
                else:
                    # QSNY = str(QSRQ[:4])+str(QSRQ[5:7])
                    # QZNY = str(QZRQ[:4])+str(QZRQ[5:7])
                    Mons = (int(QZRQ[:4])-int(QSRQ[:4]))*12 + (int(QZRQ[5:7])-int(QSRQ[5:7]))
                    noneCount = 0
                    if(Mons==0):
                        ND = QSRQ[:4]
                        YF = QSRQ[5:7]
                        # noneCount = 0
                        if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                               '08', '09', '10', '11', '12']:
                            #NDYF1=datetime.datetime.strptime(NDYF, '%Y-%m')
                            # “应征增值税货物及劳务不含税销售额(YZZZSHWJLWBHSXSEBNBQ)”
                            if isfloat(i.get('YZZZSHWJLWBHSXSEBNBQ')):
                                a1 = float(i.get('YZZZSHWJLWBHSXSEBNBQ'))
                            else:
                                a1 = None
                                noneCount += 1
                            # “销售、出租不动产不含税销售额(XSCZBDCBHSXSE)”
                            if isfloat(i.get('XSCZBDCBHSXSE')):
                                a2 = float(i.get('XSCZBDCBHSXSE'))
                            else:
                                a2 = None
                                noneCount += 1
                            # “销售使用过的应税固定资产不含税销售额(XSSYGDYSGDZCBHSXSEBNBQ)”
                            if isfloat(i.get('XSSYGDYSGDZCBHSXSEBNBQ')):
                                a3 = float(i.get('XSSYGDYSGDZCBHSXSEBNBQ'))
                            else:
                                a3 = None
                                noneCount += 1
                            # “免税货物及劳务销售额(MSHWJLWXSEBNBQ)”
                            if isfloat(i.get('MSHWJLWXSEBNBQ')):
                                a4 = float(i.get('MSHWJLWXSEBNBQ'))
                            else:
                                a4 = None
                                noneCount += 1
                            #出口免税货物销售额(CKMSHWXSEBNBQ)
                            if isfloat(i.get('CKMSHWXSEBNBQ')):
                                a5 = float(i.get('CKMSHWXSEBNBQ'))
                            else:
                                a5 = None
                                noneCount += 1
                            # 字段都有问题
                            if noneCount == 5:
                                pass
                            elif a1==a2==a1==a3==a4==a5==None:
                                pass
                            else:
                                # 存入每个月的收入
                                if a1 == None:
                                    a1=0
                                if a2 == None:
                                    a2=0
                                if a3 == None:
                                    a3=0
                                if a4 == None:
                                    a4=0
                                if a5 == None:
                                    a5=0
                                Reven_Value = a1+a2+a3+a4+a5
                                key = str(ND) + str(YF)
                                if Reven_list.get(key) == 'None':
                                    Reven_list.update({key: Reven_Value})
                        else:
                            pass
                    elif(Mons>0):
                        # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                        if isfloat(i.get('YZZZSHWJLWBHSXSEBNBQ')):
                            a1 = float(i.get('YZZZSHWJLWBHSXSEBNBQ'))
                        else:
                            a1 = None
                            noneCount += 1
                        # “销售、出租不动产不含税销售额(XSCZBDCBHSXSE)”
                        if isfloat(i.get('XSCZBDCBHSXSE')):
                            a2 = float(i.get('XSCZBDCBHSXSE'))
                        else:
                            a2 = None
                            noneCount += 1
                        # “销售使用过的应税固定资产不含税销售额(XSSYGDYSGDZCBHSXSEBNBQ)”
                        if isfloat(i.get('XSSYGDYSGDZCBHSXSEBNBQ')):
                            a3 = float(i.get('XSSYGDYSGDZCBHSXSEBNBQ'))
                        else:
                            a3 = None
                            noneCount += 1
                        # “免税货物及劳务销售额(MSHWJLWXSEBNBQ)”
                        if isfloat(i.get('MSHWJLWXSEBNBQ')):
                            a4 = float(i.get('MSHWJLWXSEBNBQ'))
                        else:
                            a4 = None
                            noneCount += 1
                        #出口免税货物销售额(CKMSHWXSEBNBQ)
                        if isfloat(i.get('CKMSHWXSEBNBQ')):
                            a5 = float(i.get('CKMSHWXSEBNBQ'))
                        else:
                            a5 = None
                            noneCount += 1
                        # 字段都有问题
                        if noneCount == 5:
                            pass
                        elif a1==a2==a1==a3==a4==a5==None:
                            pass
                        else:
                            # 存入收入
                            if a1 == None:
                                a1=0
                            if a2 == None:
                                a2=0
                            if a3 == None:
                                a3=0
                            if a4 == None:
                                a4=0
                            if a5 == None:
                                a5=0
                            Reven_Value = a1+a2+a3+a4+a5
                            Reven_Ave = round(float(Reven_Value)/(Mons+1),4)
                            for  j in range(Mons+1):
                                NDYF = datetime.datetime.strptime(QSRQ,'%Y-%m-%d') + relativedelta(months=j)
                                ND = str(NDYF)[:4]
                                YF = str(NDYF)[5:7]
                                # noneCount = 0
                                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                                       '08', '09', '10', '11', '12']:
                                    key = str(ND) + str(YF)
                                    if Reven_list.get(key) == 'None':
                                        Reven_list.update({key: Reven_Ave})
                                    else:
                                        pass
                                else:
                                    flag.append(None)
                                    continue
                    else:
                        flag.append(None)
                        pass
            if len(flag) == len(syptZzsxgm):
                Reven_list = 'None'
            return Reven_list
    except:
        return 'None'

# 月均申报收入总和

def TX02_MonthlyIncomeReportAmt():
    try:
        syptZzsxgm = getTableTX('syptZzsXgm')
        syptZzsybnsr = getTableTX('syptZzsybnsr')
        if syptZzsxgm in [None, [{}]] and syptZzsybnsr in [None, [{}]]:
            return None
        elif syptZzsxgm not in [None, [{}]] and syptZzsybnsr in [None, [{}]]:
            Reven_list = xgm()
            if Reven_list  == 'None':
                return None
            else:
                Reven_list_Value1 = Reven_list.values()
                Reven_list_sub = OrderedDict()
                for k, v in Reven_list.items():
                    if v == 'None':
                        Reven_list_sub.update({k:0})
                    else:
                        Reven_list_sub.update({k:v})
                Reven_list_Value2 = Reven_list_sub.values()
                if  Reven_list_Value1[0] != 'None':
                    Reven2Y_Ave = round(sum(Reven_list_Value2[0:24])/24,4)
                elif Reven_list_Value1[0] == 'None' and Reven_list_Value1[1] != 'None':
                    Reven2Y_Ave = round(sum(Reven_list_Value2[1:25])/24,4)
                elif Reven_list_Value1[0] == 'None' and Reven_list_Value1[1] == 'None' and Reven_list_Value1[2] != 'None':
                    Reven2Y_Ave = round(sum(Reven_list_Value2[2:26])/24,4)
                else:
                    Reven2Y_Ave = round(sum(Reven_list_Value2[3:27])/24,4)
                return Reven2Y_Ave
        elif syptZzsxgm in [None, [{}]] and syptZzsybnsr not in [None, [{}]]:
            Reven_list = ybnsr()
            if Reven_list  == 'None':
                return None
            else:
                Reven_list_Value1 = Reven_list.values()
                Reven_list_sub = OrderedDict()
                for k, v in Reven_list.items():
                    if v == 'None':
                        Reven_list_sub.update({k:0})
                    else:
                        Reven_list_sub.update({k:v})
                Reven_list_Value2 = Reven_list_sub.values()
                if  Reven_list_Value1[0] != 'None':
                    Reven2Y_Ave = round(sum(Reven_list_Value2[0:24])/24,4)
                else:
                    Reven2Y_Ave = round(sum(Reven_list_Value2[1:25])/24,4)
                return Reven2Y_Ave
        else:
            #合并 ybnsr 和 xgm 计算
            Reven_list1 = xgm()
            Reven_list2 = ybnsr()
            Reven_list = OrderedDict()
            # 二者同时为空 才返回空
            if Reven_list1 == 'None' and Reven_list2 == 'None':
                Reven_list = None
            elif  Reven_list1 != 'None' and Reven_list2 == 'None':
                Reven_list = Reven_list1
            elif  Reven_list1 == 'None' and Reven_list2 != 'None':
                Reven_list = Reven_list2
            else:
                #纳税类型
                taxerType = TaxerType()
                # 一般纳税人,优先取一般纳税人
                if taxerType in ['201', '202', '203']:
                    for k, v in Reven_list2.items():
                        if v == 'None':
                            tmp = Reven_list1.get(k)
                            if tmp != 'None':
                                Reven_list.update({k:tmp})
                            else:
                                Reven_list.update({k:'None'})
                        else:
                            Reven_list.update({k:v})
                # 小规模,优先取小规模
                elif taxerType in ['204', '205']:
                    for k, v in Reven_list1.items():
                        if v == 'None':
                            tmp = Reven_list2.get(k)
                            if tmp != 'None':
                                Reven_list.update({k:tmp})
                            else:
                                Reven_list.update({k:'None'})
                        else:
                            Reven_list.update({k:v})
                #其他情况
                else:
                    # 取出小规模纳税人表 和 一般纳税人表中 缴税年度和月份进行比较
                    ybnsr_list = []
                    xgm_list = []
                    for i in syptZzsxgm:
                        QZRQ = i.get('skssqz')
                        if QZRQ in null_type_list or formatDate(QZRQ) == None:
                            pass
                        else:
                            NDYF = datetime.datetime.strptime(QZRQ,'%Y-%m-%d')
                            ND = str(NDYF)[:4]
                            YF = str(NDYF)[5:7]
                            # ND = i.get('ND')
                            # YF = i.get('YF')
                            try:
                                d = float(ND + YF)
                            except:
                                continue
                            if isfloat(d):
                                xgm_list.append(float(d))
                            else:
                                pass
                    for i in syptZzsybnsr:
                        QZRQ = i.get('skssqz')
                        if QZRQ in null_type_list or formatDate(QZRQ) == None:
                            pass
                        else:
                            NDYF = datetime.datetime.strptime(QZRQ,'%Y-%m-%d')
                            ND = str(NDYF)[:4]
                            YF = str(NDYF)[5:7]
                            # ND = i.get('ND')
                            # YF = i.get('YF')
                            try:
                                d = float(ND + YF)
                            except:
                                continue
                            if isfloat(d):
                                ybnsr_list.append(float(d))
                            else:
                                pass
                    if ybnsr_list == [] and xgm_list == []:
                        Reven_list = None
                    elif ybnsr_list != [] and xgm_list != []:
                        if max(ybnsr_list) >= max(xgm_list):
                            for k, v in Reven_list2.items():
                                if v == 'None':
                                    tmp = Reven_list1.get(k)
                                    if tmp != 'None':
                                        Reven_list.update({k:tmp})
                                    else:
                                        Reven_list.update({k:'None'})
                                else:
                                    Reven_list.update({k:v})
                        else:
                             for k, v in Reven_list1.items():
                                if v == 'None':
                                    tmp = Reven_list2.get(k)
                                    if tmp != 'None':
                                        Reven_list.update({k:tmp})
                                    else:
                                        Reven_list.update({k:'None'})
                                else:
                                    Reven_list.update({k:v})
                    elif ybnsr_list != [] and xgm_list == []:
                        for k, v in Reven_list2.items():
                            if v == 'None':
                                tmp = Reven_list1.get(k)
                                if tmp != 'None':
                                    Reven_list.update({k:tmp})
                                else:
                                    Reven_list.update({k:'None'})
                            else:
                                Reven_list.update({k:v})
                    elif ybnsr_list == [] and xgm_list != []:
                        for k, v in Reven_list1.items():
                            if v == 'None':
                                tmp = Reven_list2.get(k)
                                if tmp != 'None':
                                    Reven_list.update({k:tmp})
                                else:
                                    Reven_list.update({k:'None'})
                            else:
                                Reven_list.update({k:v})
                    else:
                        assert False
            if Reven_list in null_type_list:
                return None
            else:
                Reven_list_Value1 = Reven_list.values()
                Reven_list_sub = OrderedDict()
                for k, v in Reven_list.items():
                    if v == 'None':
                        Reven_list_sub.update({k:0})
                    else:
                        Reven_list_sub.update({k:v})
                Reven_list_Value2 = Reven_list_sub.values()
                # 纳税类型
                taxerType = TaxerType()
                # 一般纳税人,优先取一般纳税人
                if taxerType in ['201', '202', '203']:
                    if Reven_list_Value1[0] != 'None':
                        Reven2Y_Ave = round(sum(Reven_list_Value2[0:24]) / 24, 4)
                    else:
                        Reven2Y_Ave = round(sum(Reven_list_Value2[1:25]) / 24, 4)
                else:
                    if Reven_list_Value1[0] != 'None':
                        Reven2Y_Ave = round(sum(Reven_list_Value2[0:24]) / 24, 4)
                    elif Reven_list_Value1[0] == 'None' and Reven_list_Value1[1] != 'None':
                        Reven2Y_Ave = round(sum(Reven_list_Value2[1:25]) / 24, 4)
                    elif Reven_list_Value1[0] == 'None' and Reven_list_Value1[1] == 'None' and Reven_list_Value1[
                        2] != 'None':
                        Reven2Y_Ave = round(sum(Reven_list_Value2[2:26]) / 24, 4)
                    else:
                        Reven2Y_Ave = round(sum(Reven_list_Value2[3:27]) / 24, 4)
                return Reven2Y_Ave
    except:
        return None



def EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro():
    Factor1= Later6MonsUpaidLoanBalPre()
    Factor2 = TX02_MonthlyIncomeReportAmt()
    if Factor1==0 and Factor2==0:
        return 0
    elif Factor1 is None or Factor2 is None:
        return u'缺失值'
    else:
        try:
            result = float(Factor1) / float(Factor2)
        except:
            return u"缺失值"
        return round(result, 4)

result = EC07_Later6MonsUpaidLoanBalToTaxMonthlyIncomePro()


